<template>
  <div style="padding: 10px; display: flex; flex-direction: column; height: 100%;">
    <el-form ref="equipmentInfoFormRef" :model="form" :rules="rules" label-width="120px" :inline="true" style="height: calc(100% - 100px); display: flex; flex-direction: column;">
      <div>
        <h3 style="font-weight: 700;margin-left: 20px;">基本信息</h3>
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编码">
          <el-tooltip :content="form.equipmentCode" placement="top">
            <div style="width: 200px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{ form.equipmentCode }}</div>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="设备一级类型" prop="equipmentTypeLevel1Id">
          <el-select v-model="form.equipmentTypeLevel1Id" v-loading="equipmentTypeLoading" placeholder="请选择设备一级类型" clearable style="width: 200px;" @change="getEquipmentTypeLevel2List">
            <el-option v-for="item in equipmentTypeLevel1List" :key="item.equipmentTypeId" :label="item.equipmentTypeName" :value="item.equipmentTypeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备二级类型" prop="equipmentTypeLevel2Id">
          <el-select v-model="form.equipmentTypeLevel2Id" v-loading="equipmentTypeLoading" placeholder="请选择设备二级类型" clearable style="width: 200px;">
            <el-option v-for="item in equipmentTypeLevel2List" :key="item.equipmentTypeId" :label="item.equipmentTypeName" :value="String(item.equipmentTypeId)" />
          </el-select>
        </el-form-item>

        <el-form-item label="安装位置" prop="positionIdList">
          <el-cascader v-model="form.positionIdList" :options="parkPlaceList" :props="{ value: 'id', label: 'label', checkStrictly: true }" />
        </el-form-item>

        <el-form-item label="是否作为巡查点" prop="patrolInspectionFlag">
          <el-switch v-model="form.patrolInspectionFlag" active-value="1" inactive-value="0" style="width: 200px" />
        </el-form-item>

        <el-form-item label="是否启用" prop="status">
          <el-select v-model="form.status" style="width: 200px" placeholder="请选择">
            <el-option label="禁用" :value="0" />
            <el-option label="启用" :value="1" />
            <el-option label="作废" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="设备性质" prop="equipmentNature">
          <el-radio-group v-model="form.equipmentNature">
            <el-radio value="1">物联设备</el-radio>
            <el-radio value="2">非物联设备</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="设备识别码" prop="deviceId">
          <el-tooltip :content="form.deviceId" placement="top">
            <div style="width: 200px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">{{ form.deviceId }}</div>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="设备分组" prop="groupId">
          <el-select v-model="form.groupId" style="width: 200px" placeholder="请选择">
            <el-option v-for="item in equipmentFireGroupList" :key="item.equipmentFireGroupId" :label="item.fireGroupName" :value="item.equipmentFireGroupId" />
          </el-select>
        </el-form-item>
      </div>
      <div>
        <h3 style="font-weight: 700;margin-left: 20px;">厂家信息</h3>
        <el-form-item label="厂家名称" prop="manufacturerName">
          <el-input v-model="form.manufacturerName" placeholder="请输入厂家名称" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactsName">
          <el-input v-model="form.contactsName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="质保期" prop="warrantyPeriod">
          <el-date-picker v-model="form.warrantyPeriod" type="date" placeholder="请选择质保期" style="width: 200px;" />
        </el-form-item>
      </div>

      <div>
        <h3 style="font-weight: 700;margin-left: 20px;">更多信息</h3>

        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注说明" :autosize="{ minRows: 3, maxRows: 3 }" style="width: 500px" />
        </el-form-item>
      </div>

      <div>
        <h3 style="font-weight: 700;margin-left: 20px;">文档附件</h3>
        <el-form-item label="上传附件">
          <FileUpload v-model="form.fileIdList" />
        </el-form-item>
      </div>
    </el-form>

    <div style="height: 70px; display: flex; justify-content: center; align-items: end;">
      <el-button :loading="buttonLoading" :disabled="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="emit('close')">取 消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { getEquipmentInfo, updateEquipmentInfo } from '@/api/facility/equipment-info';
import { parkTree } from '@/api/access/parking-lot/parking-lot-place';
import useUserStore from '@/store/modules/user';
import request from '@/utils/request';

const emit = defineEmits(['close', 'success']);
const props = defineProps({
  equipmentId: {
    type: String,
    required: true
  }
});

const userStore = useUserStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const equipmentInfoFormRef = ref<ElFormInstance>();
let parkPlaceList = ref([]);
const parkPlaceLoading = ref(false);

const form = ref<any>({
  deviceName: undefined,
  equipmentId: undefined,
  nodeId: undefined,
  remark: undefined,
  equipmentTypeLevel1Id: 4,
  equipmentName: undefined,
  equipmentCode: undefined,
  onlineStatus: undefined,
  positionIdList: [],
  dataSource: undefined,
  deviceId: undefined,
  groupType: 2 // 分组类型（1：摄像头；，2：消防设备；10：会议室；）
});

const rules = ref<any>({
  deviceName: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  equipmentCode: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  equipmentOneType: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  equipmentTypeId: [
    { required: true, message: '不能为空', trigger: 'change' }
  ],
  positionIdList: [
    { required: true, message: '不能为空', trigger: 'change' }
  ],
  nodeId: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  equipmentModel: [
    { required: true, message: '不能为空', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '不能为空', trigger: 'change' }
  ]
})

/** 获取设备详情 */
const getEquipmentDetail = async()=>{
  proxy?.$modal.loading('加载中...')
  const res: any = await getEquipmentInfo(props.equipmentId).finally(() => proxy?.$modal.closeLoading());
  console.log('获取设备详情：', res)

  //  回显园区区域
  res.data.positionIdList = []
  if (res.data.parkBuildingId) {
    res.data.positionIdList.push(res.data.parkBuildingId)
    if (res.data.parkBuildingAreaId) {
      res.data.positionIdList.push(res.data.parkBuildingAreaId)
      if (res.data.parkBuildingFloorId) {
        res.data.positionIdList.push(res.data.parkBuildingFloorId)
        if (res.data.parkBuildingRoomId) {
          res.data.positionIdList.push(res.data.parkBuildingRoomId)
        }
      }
    }
  }

  form.value = res.data;
}

/**
 * 获取消防设备分组
 */
const equipmentFireGroupLoading = ref(false)
const equipmentFireGroupList = ref([])
const getEquipmentFireGroupList = async () => {
  equipmentFireGroupLoading.value = true
  const res = await request({ url: '/equipment/equipment-fire-group/list', method: 'get' }).finally(() => equipmentFireGroupLoading.value = false)
  console.log('获取消防设备分组：', res)

  equipmentFireGroupList.value = res.rows
}

/** 获取园区区域 */
const getPlaceList = async () => {
  parkPlaceLoading.value = true;
  const res = await parkTree().finally(() => parkPlaceLoading.value = false);
  console.log('获取园区区域：', res)
  parkPlaceList.value = res.data;
};

/** 获取设备类型 */
let equipmentTypeLoading = ref(false)
const equipmentTypeList = ref([])
const equipmentTypeLevel1List = ref([])
const equipmentTypeLevel2List = ref([])
/** 获取设备类型列表*/
const getEquipmentTypeList = ()=> {
  equipmentTypeLoading.value = true
  request({
    url: '/equipment/equipment-type/list',
    method: 'get'
  }).then((res) => {
    console.log('获取设备类型列表：', res)
    equipmentTypeList.value = res.data
    equipmentTypeLevel1List.value = res.data.filter(item => item.parentId == 0)
    equipmentTypeLevel2List.value = res.data.filter(item => item.parentId != 0 && item.parentId == 4)
  }).finally(() => { equipmentTypeLoading.value = false; })
}

/** 根据设备类型一级id获取设备类型二级列表 */
const getEquipmentTypeLevel2List = (equipmentTypeLevel1Id: number) => {
  if (equipmentTypeLevel1Id == null) {
    equipmentTypeLevel2List.value = equipmentTypeList.value.filter(item => item.parentId != 0)
  } else {
    equipmentTypeLevel2List.value = equipmentTypeList.value.filter(item => item.parentId == equipmentTypeLevel1Id)
  }
}

/** 提交按钮 */
const submitForm = () => {
  equipmentInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.parkBuildingId = form.value.positionIdList[0];
      form.value.parkBuildingAreaId = form.value.positionIdList[1];
      form.value.parkBuildingFloorId = form.value.positionIdList[2];
      form.value.parkBuildingRoomId = form.value.positionIdList[3];
      form.value.groupType = 2 // 分组类型（1：摄像头；，2：消防设备；10：会议室；）
      buttonLoading.value = true;
      await updateEquipmentInfo(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');
      emit('close');
      emit('success', form.value);
    }
  });
};

onMounted(()=>{
  getEquipmentDetail()
  getPlaceList();
  getEquipmentTypeList();
  getEquipmentFireGroupList();
})
</script>
<style lang="scss" scoped>
.descriptions{
  margin:10px 0;
}
::v-deep .el-descriptions__label{
  width: 100px;
  display: inline-block;
}
::v-deep .el-descriptions__content {
  color: black;
}
</style>

